package com.cosina.game.crystallight.model.enemy;

import android.graphics.PointF;

import com.cosina.game.crystallight.engine.util.Time;
import com.cosina.game.crystallight.model.crystal.Crystal;
import com.cosina.game.crystallight.model.crystal.Tower;

public class Ps implements Time {
	
	public static final int SIDE_LENGTH = 10;
	public final PointF location;
	private float totalSpeed = 16.0f;
	
	private float speedX, speedY;
	private final Enemy enemy;
	public final int color;
	public boolean alive = true;
	
	public int attack;
	
	public Ps(Tower tower, Enemy enemy, Crystal crystal) {
		this.location = new PointF(tower.center);
		this.enemy = enemy;
		this.color = crystal.color;
		this.attack = crystal.weapon.getAttack();
		float xDistance = enemy.center.x - location.x;
		float yDistance = enemy.center.y - location.y;
		
		float distance = PointF.length(xDistance, yDistance);
		
		speedX = Math.abs(xDistance/distance*totalSpeed);
		speedY = Math.abs(yDistance/distance*totalSpeed);
	}

	private void fly(){
		location.offset(enemy.lastMove.x, enemy.lastMove.y);
		float xDistance = enemy.center.x - location.x;
		float yDistance = enemy.center.y - location.y;
		
		if(xDistance > speedX){
			xDistance -= speedX;
		}else if(xDistance < -speedX){
			xDistance += speedX;
		}else{
			xDistance = 0;
		}
		
		if(yDistance > speedY){
			yDistance -= speedY;
		}else if(yDistance < -speedY){
			yDistance += speedY;
		}else{
			yDistance = 0;
		}
		
		if(Math.abs(xDistance) <= 4 && Math.abs(yDistance) <= 4){
			enemy.hit(this);
			this.alive = false;
		}
		this.location.set(enemy.center.x - xDistance, enemy.center.y - yDistance);
	}

	@Override
	public void withTimeGo() {
		if(enemy.isDead()){
			this.alive = false;
			return ;
		}
		fly();
	}
}
